package com.guyan.controller;

import com.github.pagehelper.PageInfo;
import com.guyan.entity.Category;
import com.guyan.form.CategoryForm;
import com.guyan.form.CategoryUpdateForm;
import com.guyan.service.CategoryService;
import com.guyan.vo.CategoryTreeVo;
import com.guyan.vo.LayuiVo;
import com.guyan.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * ClassName： CategoryController
 * Date： 2021/5/31 15:45
 *
 * @author 孤焰
 * @version 1.0
 **/

@Controller
@RequestMapping("/category")
@ResponseBody
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/categoryLeafList")
    public ResultVo categoryLeafList() {
        return ResultVo.success(categoryService.categoryLeafList());
    }

    @GetMapping("/categoryLeafListPage")
    public LayuiVo categoryLeafListPage(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer limit,
                                        String search) {
        // TODO search变量中文在前端控制台显示乱码
        PageInfo pageInfo = categoryService.categoryLeafListPage(page, limit, search);

        return LayuiVo.success(pageInfo.getTotal(), pageInfo.getList());
    }

    // TODO 类别更新状态按钮存在bug
    @PostMapping("/updateCategoryById")
    public ResultVo updateCategoryById(@RequestBody @Valid CategoryUpdateForm categoryForm, BindingResult bindingResult) {
        if (bindingResult.getErrorCount() > 0) {
            return ResultVo.error(7000, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryForm, category);

        return categoryService.updateCategoryById(category);
    }

    @GetMapping("/categoryTreeList")
    public List<CategoryTreeVo> categoryTreeList() {
        return categoryService.categoryTreeList();
    }

    @PostMapping("/addCategory")
    public ResultVo addCategory(@RequestBody @Valid CategoryForm categoryForm, BindingResult bindingResult) {
        if (bindingResult.getErrorCount() > 0) {
            return ResultVo.error(7000, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryForm, category);
        if (categoryForm.getParentId() == null) {
            category.setParentId(0);
        } else {
            System.out.println(categoryForm.getParentId());
        }

        return categoryService.addCategory(category);
    }

    @PostMapping("/delCategory")
    public ResultVo delCategory(Integer id) {
        return categoryService.delCategory(id);
    }
}
